/**
 * Copyright 2009 Sergio Bossa
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.googlecode.actorom.impl.remote.channel;

import com.googlecode.actorom.impl.remote.channel.protocol.CommandResponse;
import com.googlecode.actorom.impl.remote.channel.protocol.MessageCommand;
import java.io.IOException;
import java.net.InetSocketAddress;
import net.jcip.annotations.ThreadSafe;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Sergio Bossa
 */
@ThreadSafe
public class MessageChannelConnector {

    private static final transient Logger LOG = LoggerFactory.getLogger(MessageChannelConnector.class);
    private final String host;
    private final int port;
    private final IoConnector connector;
    private IoSession session;

    public MessageChannelConnector(String host, int port) {
        this.host = host;
        this.port = port;
        connector = new NioSocketConnector();
        connector.getSessionConfig().setUseReadOperation(true);
        connector.getFilterChain().addLast(ObjectSerializationCodecFactory.class.getName(), new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
        connector.setHandler(new IoHandlerAdapter());
    }

    public synchronized void connect() throws IOException {
        if (session == null) {
            ConnectFuture connection = connector.connect(new InetSocketAddress(host, port));
            connection.awaitUninterruptibly();
            if (connection.isConnected()) {
                LOG.info("Connected to message channel at: {}:{}", host, port);
                session = connection.getSession();
            } else {
                throw new IllegalStateException("Error connecting to " + host + ":" + port);
            }
        } else {
            throw new IllegalStateException("Already connected to " + host + ":" + port);
        }
    }

    public synchronized void disconnect() {
        if (session != null) {
            session.close(false).awaitUninterruptibly();
            connector.dispose();
            session = null;
            LOG.info("Disconnected from message channel at: {}:{}", host, port);
        }
    }

    public synchronized boolean send(MessageCommand command) {
        if (session != null) {
            session.write(command);
            Object response = session.read().awaitUninterruptibly().getMessage();
            if (response instanceof CommandResponse) {
                CommandResponse commandResponse = (CommandResponse) response;
                return commandResponse.isOk();
            } else {
                throw new IllegalStateException("Unexpected response of type: " + response.getClass());
            }
        } else {
            throw new IllegalStateException("Not connected to " + host + ":" + port);
        }
    }
}
